//
//  PatrolListViewController.m
//  SafeFoodManagerDemo
//
//  Created by bob on 2017/11/13.
//  Copyright © 2017年 bob. All rights reserved.
//

#import "PatrolListViewController.h"
#import "PatrolTableViewCell.h"
#import "PatrolListTableViewCell.h"
#import "PatrolListModel.h"
#import "SendPatrolViewController.h"
@interface PatrolListViewController ()

@property(nonatomic,copy)NSString*SearchKeyWord;

@end

@implementation PatrolListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title=@"检查日志";

    self.homeTableView.estimatedRowHeight=70;
    
    [self.homeTableView registerNib:[UINib nibWithNibName:@"PatrolTableViewCell" bundle:nil] forCellReuseIdentifier:@"Dcell"];
    
      [self.homeTableView registerNib:[UINib nibWithNibName:@"PatrolListTableViewCell" bundle:nil] forCellReuseIdentifier:@"Ucell"];
    
    [self.homeTableView.mj_header beginRefreshing];
    // Do any additional setup after loading the view.
}

#pragma mark-tablevie代理方法

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    
    return self.dataArr.count;
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    return 2;
}


-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    PatrolListData *data=self.dataArr[indexPath.section];
    
    if (indexPath.row==0) {
        
        PatrolListTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"Ucell" forIndexPath:indexPath];
       
        cell.deleStatue=self.deleStatue;//是否编辑状态
        
        cell.Data=data;
        
        return cell;
    }else{
        
        PatrolTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"Dcell" forIndexPath:indexPath];
        
          cell.Data=data;
        
        return cell;
        
        
    }
    
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row==0) {
        
        return UITableViewAutomaticDimension;
    }
    return 44;
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
     PatrolListData *data=self.dataArr[indexPath.section];
    if (self.isdeleMore) {

        if (self.deleStatue) {
            
            data.Seleclt=!data.Seleclt;
            
            [self ChangeStatues];
            
            [self.homeTableView reloadData];
            
            
        }else{
            //可以点击
            
            data.isOpen=!data.isOpen;
            
            [self.homeTableView reloadData];
          
        }
        
    }else{
        
        data.isOpen=!data.isOpen;
        
        [self.homeTableView reloadData];
        
    }
    
    
}


-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (self.isdeleMore) {
        
        return YES;
    }
    
    return NO;
    
}


-(NSString*)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return @"删除";
    
}

-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return UITableViewCellEditingStyleDelete;
    
}


-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (editingStyle==UITableViewCellEditingStyleDelete) {
        
        PatrolListData *data=self.dataArr[indexPath.section];
        
        NSMutableArray *arr=[NSMutableArray array];
        
        [arr addObject:[NSString stringWithFormat:@"%ld",data.logId]];
        
        [self DelPostion:arr];
        
    }
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    
    return 20;
}

-(void)tableView:(UITableView *)tableView willDisplayFooterView:(UIView *)view forSection:(NSInteger)section
{
    
    view.tintColor=TBColorTableViewBg;
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    
    return 0.1;
    
}

-(void)DelPostion:(NSArray*)PostID
{
    NSString *params=[HelpWay arrToJSON:PostID];
    
    [self showLoadingAnimation];
    
    BaseReqApi *api=[[BaseReqApi alloc]initWithRequestUrl:@"/index.php/FoodCheckApi/patrolDel.json" andrequestTime:5 andParams:@{@"logIds":params,@"staffId":[NSString stringWithFormat:@"%ld",[LoginStatuesModel getStaffId]]} andRequestMethod:YTKRequestMethodPOST andCache:NO andCacheTime:0 andPostToken:YES];
    
    [api StarRequest:^(TBResponseStatus responseStatus, NSString *message, id responseObject) {
        [self stopLoadingAnimation];
        
        if (responseStatus==1) {
            
            [MBProgressHUD showSuccessMessage:@"删除成功"];
            
            [self.homeTableView.mj_header beginRefreshing];
            
            if (self.deleStatue) {
                //如果处于删除状态
                [self GotoEdit:self.btn];
            }
            
        }else if (responseStatus==0)
        {
            
            [MBProgressHUD showErrorMessage:message];
            
        }else if (responseStatus==2)
        {
            [MBProgressHUD showErrorMessage:message];
            
        }else{
            
            [UIAlertView bk_showAlertViewWithTitle:message message:nil cancelButtonTitle:@"取消" otherButtonTitles:@[@"确定"] handler:^(UIAlertView *alertView, NSInteger buttonIndex) {
                
                if (buttonIndex==1) {
                    
                    [self GotoLoginVC];
                }
                
            }];
            
        }
    }];
    
    
}


#pragma mark-跳转事件
-(void)PushChangeStatueVC
{
     BOOL isSelf=self.Reqmodel.shopId==0?YES:NO;
    
    BaseSearchChooseViewController *Choose=[[BaseSearchChooseViewController alloc]init];
    
    Choose.ReqStr=[SearchAndChooseManager getChooseUrlWithType:PatrolListType];
    
    
    if (isSelf) {
        
        if ([self.Reqmodel.ptype isEqualToString:@"1"]) {
            
               Choose.CustomArr=[SearchAndChooseManager GetChooseDateWithType:PatrolListType andIsLookSelf:isSelf];
            
        }else if ([self.Reqmodel.ptype isEqualToString:@"2"])
        {
         
            NSArray *PostArr= [USER_DEFAULT objectForKey:@"TBChoose"];//如果本地存在则读取本地的
            
            if (PostArr.count!=0) {
                
                Choose.CustomArr=PostArr;
                
            }else{
            
               Choose.CustomArr=@[@{@"fieldName":@"marketIds",@"name":@"开办方",@"value":@""},@{@"fieldName":@"type",@"name":@"",@"value":@""},@{@"fieldName":@"checkUserIds",@"name":@"检查员",@"value":@""},@{@"fieldName":@"startDate",@"name":@"开始日期",@"value":@""},@{@"fieldName":@"endDate",@"name":@"结束日期",@"value":@""}];
            }
        }
        
    }else{
        
    Choose.CustomArr=[SearchAndChooseManager GetChooseDateWithType:PatrolListType andIsLookSelf:isSelf];
    }
    Choose.SearchPlace=self.searchName;
    
    Choose.KeyWord=self.SearchKeyWord;
    
     Choose.Lshopid=self.Reqmodel.shopId;
    
    Choose.SureBlock=^(NSString *paras,NSString*keyword)
    {
        self.Reqmodel.params=paras;
        
          self.SearchKeyWord=keyword;
        
        [self.homeTableView.mj_header beginRefreshing];
    };
    
    [self.navigationController pushViewController:Choose animated:YES];
}
#pragma mark-编辑事件
-(void)GotoEdit:(UIButton*)sender
{
    sender.selected=!sender.selected;
    
    self.deleStatue=sender.selected;
    
    if (!self.deleStatue) {
        
        for (PatrolListData *data in self.dataArr) {
            
            data.Seleclt=NO;
            
        }
        
        [self ChangeStatues];
    }
    
    [self.homeTableView reloadData];
}


-(void)SeletAll
{
    
    for (PatrolListData *data in self.dataArr) {
        
        data.Seleclt=YES;
        
    }
    
    [self ChangeStatues];
    [self.homeTableView reloadData];
    
}//全选

-(void)CanseletAll{
    
    for (PatrolListData *data in self.dataArr) {
        
        data.Seleclt=NO;
        
    }
    
    [self ChangeStatues];
    [self.homeTableView reloadData];
    
}//取消全选

-(void)DelectAll
{
    NSMutableArray *arr=[NSMutableArray array];
    
    for (PatrolListData *data in self.dataArr) {
        
        if (data.Seleclt) {
            
            [arr addObject:[NSString stringWithFormat:@"%ld",data.logId]];
            
        }
        
    }
    
    if (arr.count==0) {
        
        [MBProgressHUD showWarnMessage:@"请至少选择一项"];
        
        return;
    }
    
    [self DelPostion:arr];
}//全部删除


-(void)ChangeStatues{
    
    NSInteger i=0;
    
    for (PatrolListData *data in self.dataArr) {
        
        if (data.Seleclt) {
            i++;
        }
    }
    
    [self.DeleView SelectNum:i];
}

#pragma mark-新增事件
-(void)addNewgoods
{
    //新增商品
    SendPatrolViewController *sendPat=[SendPatrolViewController new];
    
    sendPat.Postmodel=self.Reqmodel;
    
    sendPat.shopName=self.shopName;
    
    sendPat.block=^()
    {
      
        [self.homeTableView.mj_header beginRefreshing];
        
    };
    
    [self.navigationController pushViewController:sendPat animated:YES];
    
}

#pragma mark-空白页点击事件
- (void)actionTapEmptyDataSetNodataView
{
    [self.homeTableView.mj_header beginRefreshing];
    
}


/**
 *  MJ头部刷新(封装层方法, 需要子类继承或者重写)
 */
- (void)actionMJHeaderRefresh
{
    self.Reqmodel.currentPage=1;
    
    [self.homeTableView.mj_footer resetNoMoreData];
    
    [self loadDatas];
}

/**
 *  MJ底部加载(封装方法, 需要子类继承或者重写)
 */
- (void)actionMJFooterLoadMore
{
    self.Reqmodel.currentPage++;
    
    [self loadDatas];
}

-(void)loadDatas
{
    [self showLoadingAnimation];
    
    BaseReqApi *api=[[BaseReqApi alloc]initWithRequestUrl:@"/index.php/FoodCheckApi/patrolList.json" andrequestTime:5 andParams:self.Reqmodel.mj_keyValues andRequestMethod:YTKRequestMethodPOST andCache:NO andCacheTime:0 andPostToken:YES];
    
    [api StarRequest:^(TBResponseStatus responseStatus, NSString *message, id responseObject) {
        [self stopLoadingAnimation];
        
        PatrolListModel *InforModel=[PatrolListModel mj_objectWithKeyValues:responseObject];
        
        
        if (responseStatus==1) {
            //请求成功
   
            self.TotalNum=[NSString stringWithFormat:@"一共找到%ld个%@",InforModel.totalRecord,@"日志"];
            
            if (InforModel.data.count==0&&self.Reqmodel.currentPage==1) {
                
                [self.dataArr removeAllObjects];
           
       
                self.Type=TBNODateType;
                
                if (self.deleStatue) {
                    //如果处于删除状态
                    [self GotoEdit:self.btn];
                }
                
                self.btn.hidden=YES;
                
                 [self.homeTableView reloadData];
                
            }else if (InforModel.data.count==0&&self.Reqmodel.currentPage!=1){
                
                self.btn.hidden=NO;
                [self.homeTableView.mj_footer endRefreshingWithNoMoreData];
                
            } else{
                
                self.btn.hidden=NO;
                
                if (self.Reqmodel.currentPage==1) {
                    
                    [self.dataArr removeAllObjects];
                    
                }
                
                [self.dataArr addObjectsFromArray:InforModel.data];
                
                [self.homeTableView reloadData];
                
            }
            
            [self NetRequestSuccess:self scrollView:self.homeTableView];
            
        }else if (responseStatus==0||responseStatus==2)
        {
            if (self.Reqmodel.currentPage>1) {
                
                self.Reqmodel.currentPage=self.Reqmodel.currentPage-1;
            }
            
            [self NetRequestFail:self scrollView:self.homeTableView msg:message];
            
            self.Type=TBReqFalie;
            
        }else{
            //404需要重新登录了
            
            [UIAlertView bk_showAlertViewWithTitle:message message:nil cancelButtonTitle:@"取消" otherButtonTitles:@[@"确定"] handler:^(UIAlertView *alertView, NSInteger buttonIndex) {
                
                if (buttonIndex==1) {
                    
                    [self GotoLoginVC];
                }
                
            }];
        }
        
    }];
    
    
}





- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
